from PyQt5.QtWidgets import QDockWidget
from qgis._core import QgsLayerTreeModel, QgsProject, QgsLayerTreeNode
from qgis._gui import QgsLayerTreeView
from logger import logger

class Tree:
    def __init__(self, layer_dock,tree_toggled):
        self.tree_toggled = tree_toggled
        self.action = None
        self.layer_dock:QDockWidget = layer_dock
        # 左侧图层控制面板
        self.layer_tree_view = QgsLayerTreeView()
        self.layer_model = QgsLayerTreeModel(QgsProject.instance().layerTreeRoot())
        self.layer_model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility, True)
        self.layer_tree_view.setModel(self.layer_model)
        QgsProject.instance().layerTreeRoot().visibilityChanged.connect(self.__sync_group_and_children)
        self.layer_dock.visibilityChanged.connect(self.__emit)

        # 设置树视图样式
        self.layer_tree_view.setStyleSheet("""
            QTreeView {
                font-family: Arial;
                font-size: 10pt;
                background-color: #FFFFFF;
                border: none;
            }
            QTreeView::item {
                padding: 3px;
            }
        """)

        self.layer_dock.setWidget(self.layer_tree_view)
        self.layer_dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.layer_dock.setMinimumWidth(300)

        # 设置停靠特性
        self.layer_dock.setFeatures(
            QDockWidget.DockWidgetMovable |
            QDockWidget.DockWidgetClosable |
            QDockWidget.DockWidgetFloatable
        )

    def get(self):
        return self.layer_dock

    def __sync_group_and_children(self, node):
        if not isinstance(node, QgsLayerTreeNode) or node.nodeType() != QgsLayerTreeNode.NodeGroup:
            return
        group = node
        group_checked = group.itemVisibilityChecked()
        for child_node in group.children():
            if child_node.itemVisibilityChecked() != group_checked:
                child_node.setItemVisibilityChecked(group_checked)
    
    def toggle_layer(self):
        logger.info("切换图层视图")
        if self.layer_dock.isVisible():
            self.layer_dock.hide()
        else:
            self.layer_dock.show()

    def __emit(self,visible):
        logger.info("图层树控制面板隐藏和现实{}",visible)
        self.tree_toggled.emit(visible)
